<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { GetStopOption } from '@/api/modules/shop'
import { GetPerformanceList } from '@/api/modules/account'
import PageNumber from '@/store/modules/PageNumberCache'

const route = useRoute()
// const router = useRouter()
const PageNumberCache = PageNumber()

const findFrom = reactive({
  RecShopId: route.query.id ? route.query.id : '~',
  OutOrderNo: '',
  WxOrderId: '',
  UserId: '',
  UserMobile: '',
  SCOpenId: '',
  Flag: '~',
  Time: [],
})
const dataList: any = reactive({
  list: [],
  shopOption: [],
})
const loading = ref(true)
const total = ref(0)
let PageSize = 20

async function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.RecShopId !== '~' && ({ RecShopId: findFrom.RecShopId })),
    ...(findFrom.OutOrderNo && ({ OutOrderNo: findFrom.OutOrderNo })),
    ...(findFrom.WxOrderId && ({ WxOrderId: findFrom.WxOrderId })),
    ...(findFrom.UserId && ({ UserId: findFrom.UserId })),
    ...(findFrom.UserMobile && ({ UserMobile: findFrom.UserMobile })),
    ...(findFrom.SCOpenId && ({ SCOpenId: findFrom.SCOpenId })),
    ...(findFrom.Flag !== '~' && ({ Flag: findFrom.Flag })),
    ...(findFrom.Time?.length > 0 && {
      FenRunStartTime: findFrom.Time[0],
      FenRunEndTime: findFrom.Time[1],
    }),
  }
  await GetPerformanceList(params).then(async (dataRes: any) => {
    if (dataRes.succeeded) {
      dataList.list = dataRes.data.items
      total.value = dataRes.data.total
      loading.value = false
    }
    else {
      ElMessage.error(`查询失败。${dataRes.errors}`)
    }
  })
  loading.value = false
}
// 查询
function Inquire() {
  GetDataList(1, PageSize)
}

// 返回
// function AddData() {
//   router.push({
//     name: 'accountIndex',
//   })
// }

// 翻页
function handleSizeChange(val: number) {
  GetDataList(1, val)
  PageSize = val
}
function handleCurrentChange(val: number) {
  GetDataList(val, PageSize)
  PageNumberCache.SetPerformancePage(val)
}

const nowPageNum = computed(() => {
  return PageNumberCache.GetPerformancePage()
})

onMounted(async () => {
  try {
    await GetStopOption().then((res) => {
      dataList.shopOption = res.data
    })

    await GetDataList(PageNumberCache.GetPerformancePage())
  }
  catch (error) {
    console.error('Error fetching data:', error)
  }
})
</script>

<template>
  <div>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="店铺">
                <el-select v-model="findFrom.RecShopId" placeholder="请选择店铺">
                  <el-option label="全部" value="~" />
                  <el-option v-for="item in dataList.shopOption" :key="item.id" :label="item.shopName" :value="`${item.id}`" />
                </el-select>
              </el-form-item>
              <el-form-item label="商户分账单号">
                <el-input v-model="findFrom.OutOrderNo" placeholder="请输入商户分账单号" clearable />
              </el-form-item>
              <el-form-item label="微信分账单号">
                <el-input v-model="findFrom.WxOrderId" placeholder="请输入微信分账单号" clearable />
              </el-form-item>
              <el-form-item label="用户ID">
                <el-input v-model="findFrom.UserId" placeholder="请输入用户ID" clearable />
              </el-form-item>
              <el-form-item label="分账人OpenId">
                <el-input v-model="findFrom.SCOpenId" placeholder="请输入分账人OpenId" clearable />
              </el-form-item>
              <el-form-item label="授权手机号">
                <el-input v-model="findFrom.UserMobile" placeholder="请输入授权手机号" clearable />
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="findFrom.Flag" placeholder="请选择状态" clearable>
                  <el-option label="全部" value="~" />
                  <el-option label="预估奖励" :value="-1" />
                  <el-option label="待发放" :value="0" />
                  <el-option label="发放成功" :value="1" />
                  <el-option label="发放失败" :value="2" />
                </el-select>
              </el-form-item>
              <el-form-item label="下单时间">
                <el-date-picker
                  v-model="findFrom.Time" type="datetimerange" clearable value-format="YYYY-MM-DD HH:mm:ss"
                  range-separator="到" start-placeholder="开始日期" end-placeholder="结束日期"
                  @keyup.enter="Inquire"
                />
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <!-- <div class="mb-5 text-right">
        <el-button @click="AddData">
          返回人员管理
        </el-button>
      </div> -->
      <el-table v-loading="loading" :data="dataList.list" stripe style="width: 100%;" border>
        <el-table-column align="center" prop="id" label="ID" width="100" />
        <el-table-column align="center" prop="orderId" label="订单ID" width="100" />
        <el-table-column align="center" prop="subscriber.userId" label="用户ID" width="120" />
        <el-table-column align="center" prop="subscriber" label="用户信息" width="200">
          <template #default="scope">
            <div v-if="!scope.row.subscriber">
              未授权
            </div>
            <div v-else class="user-name">
              <el-avatar :size="40" style="margin-right: 10px;" :src="scope.row.subscriber?.userAvatar" />
              <div>
                <p style="margin: 0;">
                  {{ scope.row.subscriber?.userNickName }}
                </p>
                <span>
                  {{ scope.row.subscriber?.userPhone }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" width="300" prop="subscriber.scOpenId" label="用户OpenID" />
        <el-table-column align="center" width="300" prop="subscriber.unionId" label="用户unionId" />
        <el-table-column align="center" prop="outOrderNo" label="商户分账单号" width="260" />
        <el-table-column align="center" prop="wxOrderId" label="微信分账单号" width="260" />
        <el-table-column align="center" prop="fenRunAmount" label="分润金额" width="260" />
        <el-table-column align="center" prop="fenRunTime" label="分润时间" width="200" />
        <el-table-column header-align="center" prop="wxDesp" label="分账描述" width="300" />
        <el-table-column align="center" prop="flag" label="账户状态" width="100">
          <template #default="scope">
            <el-tag>
              {{ scope.row.flag === -1 ? '预估奖励'
                : scope.row.flag === 0 ? '待发放'
                  : scope.row.flag === 1 ? '发放成功'
                    : scope.row.flag === 2 ? '发放失败' : '未定义' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column header-align="center" prop="wxErrCode" label="错误代码" width="300" />
        <el-table-column header-align="center" prop="wxErrCodeDes" label="错误代码描述" width="300" />
        <el-table-column header-align="center" prop="payTime" label="支付时间" width="200" />
        <el-table-column header-align="center" prop="desp" label="描述" width="300" />
        <el-table-column align="center" prop="addTime" label="添加时间" width="200" />
        <el-table-column align="center" prop="updateTime" label="更新时间" width="200" />
      </el-table>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="20"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        :default-current-page="nowPageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.user-name {
  display: flex;
  align-items: center;
  justify-content: left;
  margin-right: 25px;

  div {
    text-align: left;
  }
}
</style>
